package com.lightbox.android.photoprocessing;

import java.util.ArrayList;
import java.util.List;

import com.jihox.abookpro.R;
import com.lightbox.android.photoprocessing.crop.CropImageView;
import com.lightbox.android.photoprocessing.crop.ImageViewTouch;
import com.lightbox.android.photoprocessing.crop.ImageViewTouchBase.DisplayType;
import com.lightbox.android.photoprocessing.crop.Matrix3;
import com.lightbox.android.photoprocessing.crop.RatioItem;
import com.lightbox.android.photoprocessing.utils.BitmapUtils;
import com.lightbox.android.photoprocessing.utils.FileUtils;
import com.lightbox.android.photoprocessing.utils.MediaUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


public class PhotoCropActivity extends Activity {
	private int imageWidth, imageHeight;// 展示图片控件 宽 高
	private LoadImageTask mLoadImageTask;
	private TextView backToMenu;// 返回主菜单
	private CropImageView mCropPanel;// 剪裁操作面板
	private ImageViewTouch mainImage;
	private TextView saveCrop;
	private LinearLayout ratioList;
	private Bitmap mainBitmap;// 底层显示Bitmap
	private static List<RatioItem> dataList = new ArrayList<RatioItem>();
	private String mCurrentPhotoPath;
	private List<TextView> textViewList = new ArrayList<TextView>();

	public static int SELECTED_COLOR = Color.YELLOW;
	public static int UNSELECTED_COLOR = Color.WHITE;
	private CropRationClick mCropRationClick = new CropRationClick();
	private TextView selctedTextView;
	

	static {
		// init data
		dataList.add(new RatioItem("任意", -1f));
		dataList.add(new RatioItem("1:1", 1f));
		dataList.add(new RatioItem("1:2", 1 / 2f));
		dataList.add(new RatioItem("1:3", 1 / 3f));
		dataList.add(new RatioItem("2:3", 2 / 3f));
		dataList.add(new RatioItem("3:4", 3 / 4f));
		dataList.add(new RatioItem("2:1", 2f));
		dataList.add(new RatioItem("3:1", 3f));
		dataList.add(new RatioItem("3:2", 3 / 2f));
		dataList.add(new RatioItem("4:3", 4 / 3f));
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);	
		setContentView(R.layout.edit_image_crop);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
		
		mCurrentPhotoPath=getIntent().getStringExtra("mOriginalPhotoPath");
		mainImage = (ImageViewTouch) findViewById(R.id.main_image);
		mCropPanel = (CropImageView) findViewById(R.id.crop_panel);
		backToMenu = (TextView) findViewById(R.id.back_bt);
		ratioList = (LinearLayout)findViewById(R.id.ratio_list_group);
		saveCrop = (TextView) findViewById(R.id.save_crop);
		saveCrop.setOnClickListener(new OnClickListener() {//保存裁剪
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(selctedTextView!=null){
					saveCropImage();
				}else{
					Toast.makeText(PhotoCropActivity.this, "请先选择裁剪尺寸", Toast.LENGTH_SHORT).show();
				}
			}
		});
		backToMenu.setOnClickListener(new OnClickListener() {//返回
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		imageWidth = (int) ((float) metrics.widthPixels / 1.5);
		imageHeight = (int) ((float) metrics.heightPixels / 1.5);
		mainImage.setScaleEnabled(false);//关闭缩放
		loadImage(mCurrentPhotoPath);//加载图片
		mCropPanel.setVisibility(View.INVISIBLE);
		setUpRatioList();
	}
	

	/**
	 * 异步载入编辑图片
	 * 
	 * @param filepath
	 */
	public void loadImage(String filepath) {
		if (mLoadImageTask != null) {
			mLoadImageTask.cancel(true);
		}
		mLoadImageTask = new LoadImageTask();
		mLoadImageTask.execute(filepath);
	}

	private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
		ProgressDialog ldlog;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			String message = "正在加载图片...";
			ldlog = ProgressDialog.show(PhotoCropActivity.this, "", message);
			super.onPreExecute();
		}
		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = BitmapUtils.loadImageByPath(params[0], imageWidth,
					imageHeight);
			int angle = MediaUtils.getExifOrientation(params[0]);
			return PhotoProcessing.rotate(bitmap, angle);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (mainBitmap != null) {
				mainBitmap.recycle();
				mainBitmap = null;
				System.gc();
			}
			mainBitmap = result;
			mainImage.setImageBitmap(result);
			mainImage.setDisplayType(DisplayType.FIT_TO_SCREEN);
			ldlog.dismiss();
		}
		
	}
	//加载裁剪比率条目
	private void setUpRatioList() {
		// init UI
		ratioList.removeAllViews();
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.CENTER_VERTICAL;
		params.leftMargin = 23;
		params.rightMargin = 23;
		for (int i = 0, len = dataList.size(); i < len; i++) {
			TextView text = new TextView(this);
			text.setTextColor(UNSELECTED_COLOR);
			text.setTextSize(23);
			text.setText(dataList.get(i).getText());
			textViewList.add(text);
			ratioList.addView(text, params);
			text.setTag(i);

			dataList.get(i).setIndex(i);
			text.setTag(dataList.get(i));
			text.setOnClickListener(mCropRationClick);
		}// end for i

	}
	/**
	 * 选择剪裁比率
	 * 
	 * @author
	 * 
	 */
	private final class CropRationClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			TextView curTextView = (TextView) v;
			if(selctedTextView!=null){
				selctedTextView.setTextColor(UNSELECTED_COLOR);
			}
			RatioItem dataItem = (RatioItem) v.getTag();
			selctedTextView = curTextView;
			selctedTextView.setTextColor(SELECTED_COLOR);
			if(mCropPanel.getVisibility()!=View.VISIBLE){
				mCropPanel.setVisibility(View.VISIBLE);
			}
			mCropPanel.setRatioCropRect(mainImage.getBitmapRect(),
					dataItem.getRatio());
			// System.out.println("dataItem   " + dataItem.getText());
		}
	}// end inner class


	/**
	 * 保存剪切图片
	 */
	public void saveCropImage() {
		// System.out.println("保存剪切图片");
		CropImageTask task = new CropImageTask();
		task.execute(mainBitmap);
	}

	
	/**
	 * 图片剪裁生成 异步任务
	 * 
	 * @author panyi
	 * 
	 */
	private final class CropImageTask extends AsyncTask<Bitmap, Void, Bitmap> {
		private Dialog dialog;
		private String nsavepath;
		@Override
		protected void onCancelled() {
			super.onCancelled();
			dialog.dismiss();
		}

		@SuppressLint("NewApi")
		@Override
		protected void onCancelled(Bitmap result) {
			super.onCancelled(result);
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			String message = "正在处理...";
			dialog = ProgressDialog.show(PhotoCropActivity.this, "", message);
			dialog.show();
		}

		@Override
		protected Bitmap doInBackground(Bitmap... params) {
			RectF cropRect = mCropPanel.getCropRect();// 剪切区域矩形
			Matrix touchMatrix = mainImage.getImageViewMatrix();
			float[] data = new float[9];
			touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
			Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
			Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
			Matrix m = new Matrix();
			m.setValues(inverseMatrix.getValues());
			m.mapRect(cropRect);// 变化剪切矩形


			Bitmap resultBit = Bitmap.createBitmap(params[0],
					(int) cropRect.left, (int) cropRect.top,
					(int) cropRect.width(), (int) cropRect.height());
			nsavepath = FileUtils.savePhoto(resultBit, mCurrentPhotoPath,true);
			return resultBit;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			dialog.dismiss();
			Intent mIntent=new Intent();
			mIntent.putExtra("cropImagePath", nsavepath);
			setResult(RESULT_OK, mIntent);
			finish();
			
		}
	}// end inner class

	

}
